import QtQuick 2.0
import QtQuick.Controls 2.3
import QtCharts 2.3
import QtQuick.Layouts 1.3

Item {
    id:root
    width: 850
    height: 580*0.85
    property real minSize:  Math.min(width/850, height/(580*0.85))

    function refurbish()
    {
        readModSingal(stepScale, "B套阶跃量", -3000, 3000, 4)
        readModSingal(stepTime, "B套阶跃时间", 0, 30000, 3)
    }
    function readModSingal(handle, sqlName, min, max, point)
    {
        var t_var = $sqlMcRecorder.qml_getRegulatorVal_bystr_toint16(sqlName)
//        console.log(t_var)
        if(t_var >= min && t_var <= max)
            handle.text = String((t_var/Math.pow(10, point)).toFixed(point))
        else
            handle.text = "???"
    }
    function clearAll()
    {
        if(lineUg.count==0) return
        lineIF.clear()
        lineIgd.clear()
        lineUK.clear()
        lineUS.clear()
        lineUg.clear()
        lineUgd.clear()
    }

    onFocusChanged: {
        if(!focus) return
        refurbish()
        moveAxisToSight()
    }

    EXC_Normal_CheckBoxSytleClickable {
        id:beacon
        checkedColor:"#ff6302"
        anchors.right: parent.right
        y:10
        textSize: 25
        text: qsTr("信标开关")
        checked: false
        onCheckStateChanged: {
            markline.menabled = checked
            markline.visible = false
        }
    }

    ChartView {
        id: spline
        width: parent.width
        height: parent.height*0.83
        anchors.topMargin:  parent.height*0.05
//        title: qsTr("A通道阶跃波形")
        anchors.top: parent.top
        antialiasing:true
        legend.alignment:Qt.AlignRight
        legend.font.pixelSize: 16*root.minSize
        legend.font.family: "Verdana"
        legend.color: "#44fdfd"
        legend.labelColor: "#44fdfd"
        localizeNumbers: true
        backgroundColor: "#00000000"
        property int lineXCounter: 0

        property color colorTypeug: "#FF5052"
        property color colorTypeif: "#a077fA"
        property color colorTypeugd:  "#01de7a"
        property color colorTypeigd: "#fefe00"
        property color colorTypeuk:  "#ff9000"
        property color colorTypeus:  "#ffc904"

        Rectangle{
            id : markline
            visible: false
            color: "#8844fdfd"

            property bool menabled: false
            property int plotw: spline.plotArea.width
            property int ploth: spline.plotArea.height
            property real vug: 0
            property real vif: 0
            property real vugd: 0
            property real vigd: 0
            property real vuk: 0
            property real vus: 0

            x : spline.plotArea.x;
            y : spline.plotArea.y; // 默认在最上面

            width: spline.markline_orientation===Qt.Horizontal?plotw:2
            height: spline.markline_orientation===Qt.Horizontal?2:ploth

            Behavior on x {
                NumberAnimation {duration: 100;}
            }

            Text {
                id:markline_text
                text: "ug:\t"+parent.vug.toFixed(2)+"%\nif:\t"+parent.vif.toFixed(2)
                      +"%\nugd:\t"+parent.vugd.toFixed(2)+"%\nigd:\t"+parent.vigd.toFixed(2)
                      +"%\nuk:\t"+parent.vuk.toFixed(2)+"%\nus:\t"+parent.vus.toFixed(2)
                font.pointSize: 15
                x:10
                color: "#8844fdfd"
                state: "1"

                states: [
                    State {
                        name: "1"
                        PropertyChanges {
                            target: markline_text
                            x:10
                        }
                    },
                    State {
                        name: "2"
                        PropertyChanges {
                            target: markline_text
                            x:-markline_text.width
                        }
                    }
                ]
            }
        }
        function setMarkLine(x)
        {
            //将x的值进行转换
            var p2 = spline.mapToValue(Qt.point(x,0),lineUg);
            if(lineUg.count<3)
            {
                return
            }

            var traverseminnum = 0
            var traversemin = lineUg.at(traverseminnum)
            var traversemaxnum = lineUg.count-1
            var traversemax = lineUg.at(traversemaxnum)
            if(lineUg.at(traverseminnum).x>p2.x
                    && lineUg.at(traversemaxnum).x<p2.x) return
            for(var index=lineUg.count/2; traversemaxnum-traverseminnum>1; )
            {
                if(lineUg.at(index).x>p2.x)
                {
                    traversemaxnum = index
                    traversemax = lineUg.at(index)
                }
                else
                {
                    traverseminnum = index
                    traversemin = lineUg.at(index)
                }
                index = (traversemaxnum+traverseminnum)/2
            }
            var traverseResult
            if(p2.x>(lineUg.at(traversemaxnum).x+lineUg.at(traverseminnum).x)/2)
                traverseResult = traversemaxnum
            else traverseResult = traverseminnum

            //给信标赋值
            markline.vug = lineUg.at(traverseResult).y
            markline.vif = lineIF.at(traverseResult).y
            markline.vugd = lineUgd.at(traverseResult).y
            markline.vigd = lineIgd.at(traverseResult).y
            markline.vuk = lineUK.at(traverseResult).y
            markline.vus = lineUS.at(traverseResult).y
            //移动信标到栅格
            var traverseResultX = mapToPosition(lineUg.at(traverseResult),lineUg).x
            markline.x = traverseResultX
            if(traverseResultX>spline.width/2) markline_text.state = "2"
            else markline_text.state = "1"
        }

        Timer{
            id:markline_timer
            interval: 5000
            running: false
            repeat: false
            onTriggered: markline.visible = false
        }

        MouseArea {
            id: mouseArea
            property int xMouse
            height: parent.height*0.8
            anchors.top: parent.top
            anchors.topMargin: 0
            anchors.right: parent.right
            anchors.left: parent.left
            //存储鼠标x坐标
            acceptedButtons: Qt.LeftButton //只处理鼠标左键
            //接收鼠标按下事件
            onPressed: {
                xMouse = mouseX
                if(markline.menabled)
                {
                    spline.setMarkLine(mouseX)
                    markline.visible = true
                    markline_timer.running = false
                    markline_timer.running = true
                }
            }
            //鼠标按下后改变位置
            onPositionChanged: {
                if(markline.menabled)
                {
                    spline.setMarkLine(mouseX)
                    markline.visible = true
                    markline_timer.running = false
                    markline_timer.running = true
                    return
                }
                var t = (mouseX - xMouse)/height*(axisXA.max-axisXA.min)*0.7
                xMouse = mouseX
                var max = axisXA.max.valueOf()
                var min = axisXA.min.valueOf()
                axisXA.max = new Date(max-t*1)
                axisXA.min = new Date(min-t*1)
            }
            onWheel: {
                var max = axisXA.max.valueOf()
                var min = axisXA.min.valueOf()
                var t = wheel.angleDelta.y/360;
                var j = (axisXA.max.valueOf()-axisXA.min.valueOf())
                if(t>0 && j<11000){
                }
                else{
                    axisXA.max = new Date(max - Math.floor(j*t/2))
                    axisXA.min = new Date(min + Math.floor(j*t/2))
                }
            }
        }

        ValueAxis {
            id: axisYA
            gridLineColor: "#2246e09f"
            labelsFont.family: "Verdana"
            labelsFont.bold: false
            labelsFont.pixelSize: 12*minSize
            min: 0
            max: 120
            tickCount: 9
            labelFormat: "%.0f"
            labelsColor: "#44fdfd"
        }

        DateTimeAxis {
            id: axisXA;
            gridLineColor: "#2246e09f"
            labelsFont.bold: false
            labelsFont.family: "Arial"
            labelsFont.pixelSize: 12*minSize
            labelsColor: "#44fdfd"
            format: "HH:mm:ss"; //"yyyy MMM dd";HH:mm mm:ss
            tickCount: 9
            labelsAngle: 20
            min: new Date();
            max: new Date(new Date().valueOf()+20000)
        }

        LineSeries {
            name:"IF"
            id:lineIF
            axisX: axisXA
            axisY: axisYA
            color: spline.colorTypeug
        }

        LineSeries {
            name:"Ug"
            id:lineUg
            axisX: axisXA
            axisY: axisYA
            color: spline.colorTypeif
        }

        LineSeries {
            name:"Igd"
            id:lineIgd
            axisX: axisXA
            axisY: axisYA
            color: spline.colorTypeugd
        }

        LineSeries {
            name:"Ugd"
            id:lineUgd
            axisX: axisXA
            axisY: axisYA
            color: spline.colorTypeug
        }

        LineSeries {
            name:"US"
            id:lineUS
            axisX: axisXA
            axisY: axisYA
            color: spline.colorTypeigd
        }

        LineSeries {
            name:"UK"
            id:lineUK
            axisX: axisXA
            axisY: axisYA
            color: spline.colorTypeus
        }

        Rectangle{
            width: parent.width*0.05
            height: parent.height*0.4
            color: mouseArea_AExtend.pressed? "#4444fdfd":"#2244fdfd"
            anchors.top: parent.top
            anchors.right: parent.right
            radius: 50*root.minSize
            anchors.topMargin: parent.height*0.05
            Text {
                color: mouseArea_AExtend.pressed? "#88fa9292":"#44fa9292"
                text: qsTr("><")
                font.bold: true
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
                font.pointSize: 25*34/42
            }

            MouseArea {
                id: mouseArea_AExtend
                anchors.fill: parent
                onClicked: {
                    var max = axisXA.max.valueOf()
                    var min = axisXA.min.valueOf()
                    var step = max - min
                    axisXA.max = new Date(max + step)
                    axisXA.min = new Date(min - step)
                }
            }
        }

        Rectangle{
            width: parent.width*0.05
            height: parent.height*0.4
            color: mouseArea_ANarrow.pressed? "#4444fdfd":"#2244fdfd"
            anchors.top: parent.top
            anchors.right: parent.right
            radius: 50*root.minSize
            anchors.topMargin: parent.height*0.45
            Text {
                color: mouseArea_ANarrow.pressed? "#88fa9292":"#44fa9292"
                text: qsTr("<>")
                font.bold: true
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
                font.pointSize: 25*34/42
            }

            MouseArea {
                id: mouseArea_ANarrow
                anchors.fill: parent
                onClicked: {
                    var max = axisXA.max.valueOf()
                    var min = axisXA.min.valueOf()
                    var step = max - min
                    if(step/2>11000)
                    {
                        axisXA.max = new Date(max - step/4)
                        axisXA.min = new Date(min + step/4)
                    }
                }
            }
        }

        Rectangle{
            width: parent.width*0.04
            height: parent.height*0.8
            color: mouseArea_ALeft.pressed? "#4444fdfd":"#2244fdfd"
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.top: parent.top
            radius: 50*root.minSize
            anchors.topMargin: parent.height*0.05
            Text {
                color: mouseArea_ALeft.pressed? "#88fa9292":"#44fa9292"
                text: qsTr("<")
                font.bold: true
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
                font.pointSize: 25*34/42
            }

            MouseArea {
                id: mouseArea_ALeft
                anchors.fill: parent
                onClicked: {
                    var max = axisXA.max.valueOf()
                    var min = axisXA.min.valueOf()
                    var step = max - min
                    axisXA.max = new Date(max - step/2)
                    axisXA.min = new Date(min - step/2)
                }
            }
        }

        Rectangle{
            width: parent.width*0.04
            height: parent.height*0.8
            color: mouseArea_ARight.pressed? "#4444fdfd":"#2244fdfd"
            anchors.right: parent.right
            anchors.rightMargin: 90*parent.width/850
            anchors.top: parent.top
            radius: 50*root.minSize
            anchors.topMargin: parent.height*0.05
            Text {
                color: mouseArea_ARight.pressed? "#88fa9292":"#44fa9292"
                text: qsTr(">")
                font.bold: true
                anchors.fill: parent
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
                font.pointSize: 25*34/42
            }

            MouseArea {
                id: mouseArea_ARight
                anchors.fill: parent
                onClicked: {
                    var max = axisXA.max.valueOf()
                    var min = axisXA.min.valueOf()
                    var step = max - min
                    axisXA.max = new Date(max + step/2)
                    axisXA.min = new Date(min + step/2)
                }
            }
        }


    }

    Text {
        x: 10*root.minSize
        y: 440*root.minSize
        text: qsTr("阶跃量:")
        color: "#44fdfd"
        font.pixelSize: 22*root.minSize
    }

    Rectangle {
        width: stepScale.contentWidth<100 ? 100 : stepScale.contentWidth + 10
        height: stepScale.contentHeight + 5
        x: 88*root.minSize
        y: 440*root.minSize
        color: "#88ff7f50"
        border.color: "transparent"
        radius: 10
        TextInput {
            id: stepScale
            anchors.centerIn: parent
            x: 88*root.minSize
            y: 440*root.minSize
            text: "???"
            color: "#44fdfd"
            validator: RegExpValidator{regExp:/[0-9\.]+/}
            selectByMouse: true
            font.pixelSize: 22*root.minSize
        }
        Text {
            anchors.left: parent.right
            text: qsTr("%")
            color: "#44fdfd"
            font.pixelSize: 22*root.minSize
        }
    }

    Text {
        x: 220*root.minSize
        y: 440*root.minSize
        text: qsTr("阶跃时间:")
        color: "#44fdfd"
        font.pixelSize: 22*root.minSize
    }

    Rectangle {
        width: stepTime.contentWidth<100 ? 100 : stepTime.contentWidth + 10
        height: stepTime.contentHeight + 5
        x: 320*root.minSize
        y: 440*root.minSize
        color: "#88ff7f50"
        border.color: "transparent"
        radius: 10
        TextInput {
            id: stepTime
            anchors.centerIn: parent
            text: "???"
            color: "#44fdfd"
            validator: RegExpValidator{regExp:/[0-9\.]+/}
            selectByMouse: true
            font.pixelSize: 22*root.minSize
        }
        Text {
            text: qsTr("秒")
            anchors.left: parent.right
            font.pixelSize: 22*root.minSize
            color: "#44fdfd"
        }
    }

    EXC_Normal_BtnUncheckSecret_highStyle {
        id: button_startStep
        x: root.width*0.62
        y: 440*root.minSize
        width: parent.width*0.11
        height: parent.height*0.08
        nameFontpixelSize: 20*root.minSize
        nameText: qsTr("开始阶跃")
        onClicked:{
            refurbish()
            $modbusInterface.sl_modbusWriteImpulse($sqlMcDefine.qml_queryTableOnce('SELECT dec FROM reg_define WHERE define='+'\'A套开始阶跃\''))
        }
    }

    EXC_Normal_BtnUncheckSecret_highStyle {
        id: button_stopStep
        x: root.width*0.75
        y: 440*root.minSize
        width: parent.width*0.11
        height: parent.height*0.08
        nameFontpixelSize: 20*root.minSize
        nameText: qsTr("停止阶跃")
        onClicked:{
            refurbish()
            $modbusInterface.sl_modbusWriteImpulse($sqlMcDefine.qml_queryTableOnce('SELECT dec FROM reg_define WHERE define='+'\'A套停止阶跃\''))
        }
    }

    EXC_Normal_BtnUncheckWindowStyle {
        id: button_dayin
        x: root.width*0.88
        y: 440*root.minSize
        nameText: qsTr("打印")
        nameFontpixelSize: 20*root.minSize
        width: parent.width*0.11
        height: parent.height*0.08
        onClicked: {
            var filePathName = "../阶跃A通道 ";
            filePathName += (new Date).toLocaleString(Qt.locale(), "yyyy-MM-dd hh:mm:ss.zzz")
            filePathName += ".png";
            spline.grabToImage(function(result) {
                console.log(result.saveToFile(filePathName));
            });
        }
    }

    EXC_Normal_BtnUncheckSecret_highStyle {
        id: button6
        x: root.width*0.48
        y: 440*root.minSize
        width: parent.width*0.11
        height: parent.height*0.08
        nameFontpixelSize: 20*root.minSize
        nameText: qsTr("参数保存")
        onClicked:{
            function writeModSingal(handle, sqlName, min, max, point)
            {
                if(handle === "???") return
                var t_var = Number(handle)*Math.pow(10, point)
                console.log(t_var)
                if(t_var >= min && t_var <= max)
                    $modbusInterface.sl_modbusWriteData($sqlMcDefine.qml_queryTableRegDef(sqlName), t_var.toFixed(0))
            }
            writeModSingal(stepScale.text, "A套阶跃量", -3000, 3000, 4)
            writeModSingal(stepTime.text, "A套阶跃时间", 0, 30000, 3)
            timer_ass.start()
        }
        Timer{
            id:timer_ass
            interval: 700
            repeat: true
            triggeredOnStart: false
            property int thisCounter: 0
            onTriggered: {
                refurbish()
                thisCounter++
                if(thisCounter>3) {
                    thisCounter=0
                    stop()
                }
            }
        }
    }

    function moveAxisToSight()
    {
        var step = axisXA.max.valueOf() - axisXA.min.valueOf()
        var t_date = new Date
        axisXA.max = new Date(t_date.valueOf() + step/2)
        axisXA.min = new Date(t_date.valueOf() - step/2)
    }
    function addLinePointSingal(newTimeValueOf, whichLine, vary){

        var max = axisXA.max.valueOf()
        var min = axisXA.min.valueOf()

        if(vary<0) vary = 0
        //        if(vary>120) vary = 120

        if(spline.lineXCounter>2000){
            whichLine.remove(0)
//            spline.lineXCounter--
        }
        whichLine.append(newTimeValueOf, vary)
        if(newTimeValueOf<axisXA.max.valueOf() && (newTimeValueOf+2000)>axisXA.max){
            var step = axisXA.max.valueOf() - axisXA.min.valueOf()
            axisXA.max = new Date(max + step/2)
            axisXA.min = new Date(min + step/2)
        }
    }

    function addLinePoint(newTimeValueOf, ug, il, ugd, igd, us, uk){
        spline.lineXCounter++
        addLinePointSingal(newTimeValueOf, lineIF, il)
        addLinePointSingal(newTimeValueOf, lineUg, ug)
        addLinePointSingal(newTimeValueOf, lineIgd, igd)
        addLinePointSingal(newTimeValueOf, lineUgd, ugd)
        addLinePointSingal(newTimeValueOf, lineUS, us)
        addLinePointSingal(newTimeValueOf, lineUK, uk)

        if(spline.lineXCounter>2000){
            spline.lineXCounter--
        }
    }
}
